<template>
  <div>
    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="$parent.opendetailed" width="780px" append-to-body>
      <div class="center_dialog">
        <el-form ref="form" :model="form" :rules="rules" label-width="180px">
          <el-divider>设备信息</el-divider>
          <el-form-item label="领用设备" prop="borrowEquipments">
            <el-select v-model="form.borrowEquipments" multiple @change="SelectChange" placeholder="请选择领用设备"
              style="width:100%">
              <el-option v-for="dict in basedata" :key="dict.index"
                :label="`${dict.equipmentName}(${dict.equipmentNum})`" :value="dict.equipmentAccountId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-for="(val, index) in tagUserList" :key="index" :label="val.name" prop="estimatedReturnTime">
            <el-date-picker value-format="yyyy-MM-dd" style="width:100%" v-model="val.estimatedReturnTime" type="date"
              placeholder="请选择预计归还时间">
            </el-date-picker>
          </el-form-item>
          <el-divider>领用信息</el-divider>
          <el-form-item label="领用部门" prop="borrowDeptId">
            <el-select v-model="form.borrowDeptId" @change="systemChange(form.borrowDeptId)" placeholder="请选择领用部门"
              style="width:100%">
              <el-option v-for="dict in systemdict" :key="dict.index" :label="dict.deptName" :value="dict.deptId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="领用人" prop="borrowerId">
            <el-select v-model="form.borrowerId" placeholder="请选择领用人" style="width:100%">
              <el-option v-for="dict in userData" :key="dict.value" :label="dict.userName" :value="dict.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="领用说明" prop="explanation">
            <el-input type="textarea" v-model="form.explanation" placeholder="请输入领用说明" />
          </el-form-item>
          <!-- <el-form-item label="设备图片" prop="image">
            <Upload :imgUrl="form.image" @clearimgUrl="() => form.image = ''" @handleSuccess="handleSuccess"></Upload>
          </el-form-item> -->
          <el-form-item label="设备附件" prop="file">
            <!-- <el-upload :action="action_url" list-type="text" accept=".pdf,.docx,,.doc,.xls,.xlsx,.jpg,'.png'"
              :headers="header_url" :show-file-list="false" :on-success="handlePictureCardflie"
              :before-upload="beforeAvatarUploadflie" :on-remove="handleremoveflie" :limit="1">
              <el-button size="medium" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                上传附件支持xls,xlsx,docx,doc,pdf,jpg,png格式,大小不超过50M。
              </div>
            </el-upload>
            <template v-if="form.file">
              <el-link type="primary" icon="el-icon-document" :href="form.file" target="_blank">附件资料</el-link>
              <el-button :style="{ 'margin-left': '5px', 'position': 'relative', 'top': '2px', 'color': 'red' }"
                type="text" icon="el-icon-delete" @click="handleremoveflie">
              </el-button>
            </template> -->
            <FileUpload v-model="form.file" :limit="1" :fileSize="50"
              :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
            </FileUpload>
          </el-form-item>
        </el-form>
      </div>
      <div align="center" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="() => $parent.opendetailed = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getuserlist, getsystemlist } from '@/api/equipment/equipment.js'
import { putBorrowUpdate, postBorrow, getDictList, postPartInfolist, getChlidrenBorrow } from '@/api/management/management.js'
import Upload from '@/components/upload/index.vue'
export default {
  props: ['title', 'rowObj'],
  components: {
    Upload
  },
  data () {
    return {
      form: {
        "borrowEquipments": [
          // { "equipmentAccountId": 4 /* 设备ID */, "estimatedReturnTime": "2022-6-15" /* 预计归还日期 */ }
        ], //外借设备集合
        "borrowDeptId": undefined, //领用部门ID
        "borrowerId": undefined, //领用人ID
        "explanation": undefined, //领用说明
        "file": undefined //附件
      },
      userData: [],//负责人列表
      systemdict: [],//部门列表
      allUserData: [],//全部用户列表
      basedata: [],//设备基值列表
      Dictdata: [],
      tagUserList: [],
      rules: {
        borrowEquipments: { required: true, message: '必填', trigger: 'blur' },
        borrowDeptId: { required: true, message: '必填', trigger: 'blur' },
        borrowerId: { required: true, message: '必填', trigger: 'blur' },
      }
    }
  },
  computed: {
  },
  created () {
    this.getlist()
  },
  methods: {
    SelectChange () {
      this.tagUserList = []
      this.form.borrowEquipments.map(item => {
        this.basedata.map(value => {
          if (item === value.equipmentAccountId) {
            this.tagUserList.push({
              equipmentAccountId: value.equipmentAccountId,
              estimatedReturnTime: null,
              name: `${value.equipmentName}(${value.equipmentNum})`
            })
          }
        })
      })
    },
    handleSuccess (res) {
      console.log(res);
      this.form.image = res.res.data.url
    },
    async getlist () {
      let systemdata = await getsystemlist();//部门
      let userdata = await getuserlist();
      let basedata = await postPartInfolist({ 'params[userStatuses]': '0,1,2,4' });
      let Dictdata = await getDictList({
        dictType: 'equipment_disposal_type'
      });//设备处置状态
      this.systemdict = systemdata.data
      this.allUserData = userdata.data
      this.basedata = basedata.data
      this.Dictdata = Dictdata.data
      if (this.title === '修改') {
        this.form = { ...this.rowObj }
        this.systemChange(this.form.borrowDeptId)
        let BorrowData = await getChlidrenBorrow(this.rowObj.borrowId);
        const BorrAyyay = JSON.parse(JSON.stringify(BorrowData.data.borrowEquipmentAccountVos))
        this.form.borrowEquipments = BorrAyyay.map(item => {
          return item.eaPartInfoVo.equipmentAccountId
        })
        this.SelectChange()
        this.tagUserList.forEach((item, index) => {
          for (let index = 0; index < BorrAyyay.length; index++) {
            const element = BorrAyyay[index];
            if (item.equipmentAccountId === element.eaPartInfoVo.equipmentAccountId) {
              item.estimatedReturnTime = element.estimatedReturnTime
            }

          }
        })
      }
    },
    tagChange (val, index) {
      console.log(val);
      this.form.auditVosUser.splice(index, 1)
    },
    //提交
    submitForm () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.tagUserList.some(item => { return item.estimatedReturnTime === null })) {
            return this.$message.error('请填写完整设备预计归还时间')
          }
          if (this.title === '修改') {//修改
            let params = {
              ...this.form,
              borrowEquipments: this.tagUserList
            }
            putBorrowUpdate(params).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg)
                this.$parent.opendetailed = false
                this.$parent.getList()
              }
            })
          } else {//新增
            // { "userId": 3, /*用户ID*/ "userType": "0" /*用户类型（0审核人）*/ },
            //接口参数
            let params = {
              ...this.form,
              borrowEquipments: this.tagUserList
            }
            postBorrow(params).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg)
                this.$emit('handleUpdate')
              }
            })
          }
        }
      });
    },
    /**
     * 选择部门时触发
     */
    systemChange (value) {
      let params = {
        deptId: value//部门ID
      }
      getuserlist(params).then(res => {//查询负责人
        this.userData = res.data
      })
      this.form.borrowerId = undefined
    },
    handleremoveflie () {
      // 附件删除时调用
      this.form.file = ''
      // for (const key in this.flie) {
      //   this.flie[key] = ''
      // }
    },
    beforeAvatarUploadflie (file) {
      // 附件
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['pdf', 'docx', 'doc', 'xlsx', 'xls', 'jpg', 'png']
      const isLt2M = file.size / 1024 / 1024 < 50
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message({
          message: '上传附件支持xls,xlsx,docx,doc,pdf,jpg,png格式,大小不超过50M。',
          type: 'warning'
        })
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 50MB!')
        return false
      }
    },
    handlePictureCardflie (file) {
      // 附件成功
      // if (this.form.file !== '') {
      //   return this.$message.error('只可上传一份附件')
      // }
      console.log(file);
      this.form.file = file.data.url
    },
  }
}
</script>

<style lang="scss" scoped>
.center_dialog {
  // text-align: center;
  width: 75%;
  // padding: 0 10% 0 10%;
  box-sizing: border-box;
  margin: 0px auto;
}

.el-tag--medium {
  margin: 0px 3px;
}
</style>